package com.koo.framework.config;

import com.koo.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DBConfig {

    private static String driver;
    private static String url;

    private static String username;

    private static String password;

    private static SqlSession sqlSession;

    @Autowired
    public void setSqlSession(SqlSession sqlSession) {
        DBConfig.sqlSession = sqlSession;
    }

    @Value("spring.datasource.druid.driver-class-name")
    public void initDriverName(String driverName){
        driver = driverName;
    }
    @Value("spring.datasource.druid.url")
    public void initUrl(String path){
        url = path;
    }
    @Value("spring.datasource.druid.username")
    public void initUserName(String uname){
        username = uname;
    }
    @Value("spring.datasource.druid.password")
    public void initPassword(String pwd){
        password = pwd;
    }

    public static Connection openConnection() {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static List<Map<String, Object>> findSql(String sql) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        try {
            conn = openConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            List<String> colNameList = new ArrayList<String>();
            for (int i = 0; i < colCount; i++) {
                colNameList.add(rsmd.getColumnLabel(i + 1));
            }
            while (rs.next()) {
                Map map = new HashMap<String, Object>();
                for (int i = 0; i < colCount; i++) {
                    String key = colNameList.get(i);
                    Object value = rs.getString(colNameList.get(i));
                    map.put(key, value);
                }
                results.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (ps != null) ps.close();
                if (conn != null) conn.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return results;
    }

    /**
     * 根据表名获取表的主键列
     *
     * @param tableName 表名
     * @return 主键列名
     */
    public static String getTablePKByTableName(String tableName) {
        Connection connection = sqlSession.getConnection();
        String tablePKColumn = null;
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
            if (primaryKeys.next()) {
                tablePKColumn = primaryKeys.getString("COLUMN_NAME");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new RRException(e.getMessage());
        }
        return tablePKColumn;
    }
}  
